package com.atcumt.Thread.create;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/* 假设停车场最多可以停20辆车，现在有100辆要进入停车场。 */
public class SemaphoreTest {

    private static Semaphore semaphore = new Semaphore(20);
    public static void main(String[] args) {

        ExecutorService executorService = Executors.newFixedThreadPool(200);

        for (int i = 0; i < 100; i++) {
            executorService.execute(() -> {
                System.out.println(Thread.currentThread().getName() + "准备进入停车场==");
                // 车位判断
                if (semaphore.availablePermits() == 0) {
                    System.out.println("车辆不足，请耐心等待");
                }
                try {                   
                    semaphore.acquire(); // 获取令牌尝试进入停车场
                    System.out.println(Thread.currentThread().getName() + "成功进入停车场");                   
                    Thread.sleep(new Random().nextInt(10000)); // 模拟车辆在停车场停留的时间
                    System.out.println(Thread.currentThread().getName() + "驶出停车场");
                    
                    semaphore.release(); // 释放令牌，腾出停车场车位
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            executorService.shutdown(); // 线程池关闭
        }
    }
}
